package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"sync"
)

var (
	stack []int
	mu    sync.Mutex
)

func pushHandler(w http.ResponseWriter, r *http.Request) {
	var request struct {
		Num int `json:"num"`
	}
	
	if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
		http.Error(w, "Invalid input", http.StatusBadRequest)
		return
	}
	
	mu.Lock()
	stack = append(stack, request.Num)
	mu.Unlock()
	
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]interface{}{
		"action": "push",
		"value":  request.Num,
		"size":   len(stack),
	})
}

func popHandler(w http.ResponseWriter, r *http.Request) {
	mu.Lock()
	defer mu.Unlock()
	
	if len(stack) == 0 {
		http.Error(w, "Stack is empty", http.StatusNotFound)
		return
	}
	
	top := stack[len(stack)-1]
	stack = stack[:len(stack)-1]
	
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]interface{}{
		"action": "pop",
		"value":  top,
		"size":   len(stack),
	})
}

func main() {
	http.HandleFunc("/push", pushHandler)
	http.HandleFunc("/pop", popHandler)
	
	fmt.Println("Go stack service running on :8082")
	http.ListenAndServe(":8082", nil)
}